package com.jdy.haoduoai.activity;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.ZhifubaoPayResult;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;

//import com.alipay.sdk.app.PayTask;

public class OrderDetailsActivity extends BaseActivity implements
    OnClickListener {

  @InjectView(id = R.id.package_textview)
  private TextView mMonthTextView;

  @InjectView(id = R.id.package_money_textview)
  private TextView mMoneyTextView;

  @InjectView(id = R.id.pay_by_weixin_layout, click = true)
  private RelativeLayout mWeixinLayout;

  @InjectView(id = R.id.pay_by_zhifubao_layout, click = true)
  private RelativeLayout mZhifubaoLayout;

  private static final int ZHIFUBAO_SDK_PAY_FLAG = 1;

  private static final int ZHIFUBAO_SDK_CHECK_FLAG = 2;

  private static final String WXPAY_URL = "http://api.zhifu.letv.com/pay/wxapp/23";

  private static final String ZHIFUBAO_URL = "http://api.zhifu.letv.com/pay/mobile/3";

  public static final String QUERY_STATE_URL = "http://api.zhifu.letv.com/pay/querystat";

  private float priceToPay = 0;

  private int productId = 0;

  // -----------微信支付
  PayReq req;
  final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
  // TextView show;
  // Map<String, String> resultunifiedorder;
  // StringBuffer sb;

  private LeUser mLeUser;

  @SuppressWarnings("unused")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.order_details_layout);
    setTitle("支付订单");
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }
    Bundle b = this.getIntent().getExtras();
    String pakcageName = b.getString("packageName");
    int monthCount = b.getInt("monthCount");
    priceToPay = b.getFloat("totalMoney");
    productId = b.getInt("productId");

    mMonthTextView.setText(monthCount + "个月会员");

    mMoneyTextView.setText("￥" + priceToPay);

    // 微信支付
    req = new PayReq();
    // sb = new StringBuffer();
    msgApi.registerApp(Constant.WX_APP_ID);
  }

  @Override
  public void onClick(View v) {
    v.startAnimation(mPressedAnimation);
    switch (v.getId()) {
    case R.id.pay_by_weixin_layout:
      mPressedAnimation.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
          weixinPay();
        }
      });
      break;
    case R.id.pay_by_zhifubao_layout:
      mPressedAnimation.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
          zhifubaoPay();
        }
      });
      break;
    default:
      break;
    }
  }

  private Handler mHandler = new Handler() {
    @SuppressWarnings("unused")
    @Override
    public void handleMessage(Message msg) {
      switch (msg.what) {
      case ZHIFUBAO_SDK_PAY_FLAG: {
        final ZhifubaoPayResult payResult = new ZhifubaoPayResult(
            (String) msg.obj);

        // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
        String resultInfo = payResult.result;
        final String resultStatus = payResult.resultStatus;

        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
        if (TextUtils.equals(resultStatus, "9000")) {

          toastShow("支付成功");

          if (mLeUser == null) {
            mLeUser = Tools.restoreLeUser();
          }
          getExpiredDate(mLeUser);
        } else {
          new Thread() {
            @Override
            public void run() {
              if (Tools.isNotEmpty(LeXiaoXiaoBanApp.ordernumber)
                  && queryPayState(LeXiaoXiaoBanApp.ordernumber, "yyyyyyyyyy")) {
                runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    toastShow("支付成功");
                  }
                });
              } else {
                runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (TextUtils.equals(resultStatus, "8000")) {
                      toastShow("支付结果确认中");

                    } else {
                      // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                      toastShow(payResult.memo);

                    }
                  }
                });
              }
            };
          }.start();
        }
        break;
      }
      case ZHIFUBAO_SDK_CHECK_FLAG: {
        toastShow("检查结果为：");
        break;
      }
      default:
        break;
      }
    };
  };

  private void getExpiredDate(final LeUser lu) {
    Async.start(new Func0<ResponseResult>() {

      @Override
      public ResponseResult call() {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.GET_DEVICE_DETAIL_GET + lu.machine.id, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).filter(new Func1<ResponseResult, Boolean>() {

      @Override
      public Boolean call(ResponseResult arg0) {

        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }
    }).map(new Func1<ResponseResult, String>() {

      @Override
      public String call(ResponseResult arg0) {

        return arg0.data;
      }
    }).subscribe(new Action1<String>() {

      @Override
      public void call(String arg0) {

        if (Tools.isNotEmpty(arg0)) {
          LeMachine macInfo = JsonSerializer.getInstance().deserialize(arg0,
              LeMachine.class);

          if (macInfo != null && macInfo.activate != null) {
            LeConfig.expiredAt = macInfo.activate.expired_at;
          }
        }

      }
    });
  }

  private boolean queryPayState(String ordernumber, String sign) {
    String httpUrl = Uri.parse(QUERY_STATE_URL).buildUpon()
        .appendQueryParameter("companyid", String.valueOf(1))
        .appendQueryParameter("corderid", ordernumber)
        .appendQueryParameter("sign", sign).build().toString();

    try {
      JSONObject jsonObj = HttpUtils.initiateHttpConnection(httpUrl,
          HttpUtils.TAG_POST_REQUEST, true);
      if (jsonObj.has("status")) {
        int status = jsonObj.getInt("status");
        // 支付成功!
        if (status == 1 || status == 2) {
          return true;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return false;
  }

  @SuppressWarnings("unused")
  private String getOrderInfo(float price) {
    String httpUrl = Uri
        .parse(ZHIFUBAO_URL)
        .buildUpon()
        .appendQueryParameter("corderid", "1234567892")
        .appendQueryParameter("userid", "69261844")
        .appendQueryParameter("username", "qq_7E2A1A02FDE3C4F94E45C3C941E38FD5")
        .appendQueryParameter("companyid", String.valueOf(5))
        .appendQueryParameter("deptid", String.valueOf(130))
        .appendQueryParameter("productid", String.valueOf(2))
        .appendQueryParameter("svip", String.valueOf(0))
        .appendQueryParameter("sign", "ffc1fddc8ad3222e5490ef8b887db3e6")
        .appendQueryParameter("backurl",
            "http://api.zhifu.letv.com/tobuylepoint")
        .appendQueryParameter("price", String.valueOf(price))
        .appendQueryParameter("buyType", String.valueOf(0))
        .appendQueryParameter("chargetype", String.valueOf(1))
        .appendQueryParameter("productname", "好多爱家长版包月会员")
        .appendQueryParameter("productdesc", "好多爱家长版包月会员").build().toString();
    try {
      JSONObject jsonObj = HttpUtils.initiateHttpConnection(httpUrl,
          HttpUtils.TAG_POST_REQUEST, true);
      if (jsonObj.has("errormsg")) {
        String errorMsg = jsonObj.getString("errormsg");
        if (Tools.isEmpty(errorMsg)) {
          if (jsonObj.has("info")) {
            return jsonObj.getString("info");
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return null;
  }

  private void zhifubaoPay() {

    Async.start(new Func0<ResponseResult>() {

      @Override
      public ResponseResult call() {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        if (productId != -1) {
          param_.put(HttpUtils.TAG_PRODUCT_ID_I, String.valueOf(productId));
        }
        param_.put(HttpUtils.TAG_PAY_METHOD_I, "alipay");

        return HttpUtils.startRequest(HttpUtils.API_URL + HttpUtils.GET_PAY,
            param_, HttpUtils.TAG_GET_REQUEST);
      }

    }).filter(new Func1<ResponseResult, Boolean>() {

      @Override
      public Boolean call(ResponseResult arg0) {
        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }

    }).map(new Func1<ResponseResult, String>() {

      @Override
      public String call(ResponseResult arg0) {

        return arg0.data;
      }
    }).subscribe(new Action1<String>() {

      @Override
      public void call(final String payInfo) {
        Runnable payRunnable = new Runnable() {

          @Override
          public void run() {
            // 构造PayTask 对象
            // PayTask alipay = new PayTask(OrderDetailsActivity.this);
            // // 调用支付接口，获取支付结果
            // String result = alipay.pay(payInfo);
            //
            // Message msg = new Message();
            // msg.what = ZHIFUBAO_SDK_PAY_FLAG;
            // msg.obj = result;
            // mHandler.sendMessage(msg);
          }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
      }
    });

  }

  /**
   * 微信支付
   */
  private void startWXPay() {
    Async.start(new Func0<String>() {

      @Override
      public String call() {
        return getWXOrderInfo(priceToPay);
      }

    }).filter(new Func1<String, Boolean>() {

      @Override
      public Boolean call(String arg0) {
        return Tools.isNotEmpty(arg0);
      }

    }).subscribe(new Action1<String>() {

      @Override
      public void call(final String payInfo) {
        try {
          doWXPayWithParam(payInfo);
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    });
  }

  private void doWXPayWithParam(final String payInfoParam) throws JSONException {

    JSONObject json = new JSONObject(payInfoParam);

    if (!json.isNull("timestamp")) {
      req.timeStamp = json.getString("timestamp");
    }

    if (!json.isNull("noncestr")) {
      req.nonceStr = json.getString("noncestr");
    }

    if (!json.isNull("partnerid")) {
      req.partnerId = json.getString("partnerid");
    }

    if (!json.isNull("prepayid")) {
      req.prepayId = json.getString("prepayid");
    }

    if (!json.isNull("package")) {
      req.packageValue = json.getString("package");
    }

    if (!json.isNull("appid")) {
      req.appId = json.getString("appid");
    }

    if (!json.isNull("errcode")) {

    }

    if (!json.isNull("sign")) {
      req.sign = json.getString("sign");
    }

    if (!json.isNull("errormsg")) {

    }

    if (!json.isNull("ordernumber")) {

    }

    if (!json.isNull("status")) {

    }

    msgApi.registerApp(Constant.WX_APP_ID);
    msgApi.sendReq(req);
  }

  /**
   * 微信下单
   * 
   * @param price
   * @return
   */
  private String getWXOrderInfo(float price) {
    String httpUrl = Uri
        .parse(WXPAY_URL)
        .buildUpon()
        .appendQueryParameter("corderid", String.valueOf(1234567892))
        .appendQueryParameter("userid", String.valueOf(69261844))
        .appendQueryParameter("username", "qq_7E2A1A02FDE3C4F94E45C3C941E38FD5")
        .appendQueryParameter("companyid", String.valueOf(5))
        .appendQueryParameter("deptid", String.valueOf(130))
        .appendQueryParameter("productid", String.valueOf(2))
        .appendQueryParameter("backurl",
            "http://api.zhifu.letv.com/tobuylepoint")
        .appendQueryParameter("price", String.valueOf(price))
        .appendQueryParameter("buyType", String.valueOf(0))
        .appendQueryParameter("chargetype", String.valueOf(1))
        .appendQueryParameter("productname", "好多爱家长版包月会员")
        .appendQueryParameter("productdesc", "好多爱家长版包月会员").build().toString();
    try {
      JSONObject jsonObj = HttpUtils.initiateHttpConnection(httpUrl,
          HttpUtils.TAG_POST_REQUEST, true);

      return jsonObj.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return null;
  }

  private void weixinPay() {
    startWXPay();
    // startActivity(new Intent(this, PayActivity.class));
  }

  @Override
  protected void onDestroy() {
    if (mHandler != null) {
      mHandler.removeCallbacksAndMessages(null);
      mHandler = null;
    }
    super.onDestroy();
  }
}
